import { logout } from "@/api/index";
import { userStore } from "@/store/index";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";

Page({
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    store: userStore,
    fields: ["islogin", "userInfo"],
  },
  data: {
    logoutLoading: false,
    deleteLoading: false,

    // --- 弹窗相关状态 ---
    popupVisible: false,
    editingField: "", // 'nickName' | 'wechatId' | 'qrCode' | 'phone'
    editingTitle: "",
    tempInputValue: "" as string | number, // 弹窗中编辑的临时值
  },

  onLoad() {
    this.fetchUserProfile();
  },

  /** 更新头像 */
  onChooseAvatar(e: WechatMiniprogram.ButtonGetUserInfo) {
    const { avatarUrl } = e.detail;
    userStore.updateInfo({ avatar: avatarUrl });
    wx.showToast({ title: "头像更新成功", icon: "none" });
  },

  /** 修改性别 */
  onGenderChange() {
    wx.showActionSheet({
      itemList: ["男", "女", "保密"],
      success: (res) => {
        const gender = (res.tapIndex === 0 ? 1 : res.tapIndex === 1 ? 2 : 0) as
          | 0
          | 1
          | 2;
        userStore.updateInfo({ gender: gender });
        wx.showToast({ title: "性别已修改", icon: "none" });
      },
    });
  },

  /** 显示编辑弹窗 */
  showEditPopup(e: WechatMiniprogram.TouchEvent) {
    const { field, title } = e.currentTarget.dataset;
    const currentValue = this.data.userInfo[field as keyof IUserInfo] || "";
    this.setData({
      editingField: field,
      editingTitle: title,
      tempInputValue: currentValue,
      popupVisible: true,
    });
  },

  /** 关闭弹窗 */
  onPopupClose() {
    this.setData({ popupVisible: false });
  },

  /** 弹窗输入框内容变化 */
  onTempInputChange(e: WechatMiniprogram.Input) {
    this.setData({ tempInputValue: e.detail.value });
  },

  /** 一键获取微信昵称 */
  onGetWechatNickname(e: WechatMiniprogram.Input) {
    const nickName = e.detail.value;
    if (nickName) {
      userStore.updateInfo({ nickname: nickName });
    }
  },

  /** 选择二维码图片 */
  onChooseQrCode() {
    wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        // 实际项目中，应上传该文件到服务器，获取永久URL
        userStore.updateInfo({
          realname_auth: {
            wx: {
              qr_code: tempFilePath,
            },
          },
        });
        wx.showToast({ title: "图片选择成功", icon: "none" });
      },
    });
  },

  /** 确认编辑 */
  handleConfirmEdit() {
    const { editingField, tempInputValue } = this.data;
    if (!editingField) return;

    // 基础校验
    if (editingField === "nickName" && !tempInputValue) {
      return wx.showToast({ title: "昵称不能为空", icon: "none" });
    }
    userStore.updateInfo({ nickanem: tempInputValue });
    this.onPopupClose();

    // 模拟API保存
    wx.showLoading({ title: "保存中...", mask: true });
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({ title: "保存成功", icon: "none" });
    }, 1000);
  },

  /** 处理退出登录 */
  async handleLogout() {
    const res = await wx.showModal({
      title: "提示",
      content: "确定要退出登录吗？",
      confirmColor: "#19be6b",
    });
    if (res.confirm) {
      this.setData({ logoutLoading: true });
      userStore.logout();
      this.setData({ logoutLoading: false });
    }
  },

  /** 处理注销账户 */
  async handleDeleteAccount() {
    const res = await wx.showModal({
      title: "危险操作",
      content: "注销后账户数据将无法恢复，您确定要继续吗？",
      confirmText: "我意已决",
      confirmColor: "#f56c6c",
    });
    if (res.confirm) {
      this.setData({ deleteLoading: true });
      setTimeout(() => {
        this.setData({ deleteLoading: false });
        wx.showToast({ title: "账户已注销", icon: "none" });
        // wx.reLaunch({ url: '/pages/index/index' });
      }, 2000);
    }
  },
});
